#include "Server.h"

Server::Server(boost::asio::io_context& ioc, short port)
	:ioc_(ioc), acceptor(ioc,
		boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)) {
	std::cout << "Server start success, on port: " << port << std::endl;
	start_accept();
}
void Server::ClearSession(std::string uuid)
{
	sessions_.erase(uuid);
}
void Server::start_accept() {
	std::shared_ptr<Session> new_session = std::make_shared<Session>(ioc_, this);
	acceptor.async_accept(new_session->Socket(), std::bind(&Server::handle_accept,
		this, new_session, std::placeholders::_1));
}
void Server::handle_accept(std::shared_ptr<Session> new_session, const boost::system::error_code& ec) {
	if (ec.value()) {
		std::cout << "read error, error code: " << ec.value() <<
			" read message: " << ec.message() << std::endl;
		delete this;
		return;
	}
	new_session->start();
	sessions_.insert(std::make_pair(new_session->GetUuid(), new_session));
	this->start_accept();
}
